package com.rpa.server.servicerpaserver.crawler.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rpa.secure.servicerpasecure.common.exception.RpaRegisterException;
import com.rpa.secure.servicerpasecure.common.exception.TaskException;
import com.rpa.server.servicerpaserver.crawler.entity.Active;
import com.rpa.server.servicerpaserver.crawler.entity.Score;
import com.rpa.server.servicerpaserver.crawler.mapper.ScoreMapper;
import com.rpa.server.servicerpaserver.crawler.service.ActiveService;
import com.rpa.server.servicerpaserver.crawler.mapper.ActiveMapper;
import com.rpa.server.servicerpaserver.expose.dto.ActiveDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@Service
public class ActiveServiceImpl extends ServiceImpl<ActiveMapper, Active>
        implements ActiveService {
    @Autowired
    private ScoreMapper scoreMapper;

    @Override
    public List<Map<String, Object>> getActiveList(ActiveDto activeDto) {
        QueryWrapper<Active> activeLambdaQueryWrapper = new QueryWrapper<>();
        buildActiveWrapper(activeDto, activeLambdaQueryWrapper);
        List<Map<String, Object>> activeList = baseMapper.getActiveList(activeLambdaQueryWrapper);
        if (CollUtil.isEmpty(activeList)) {
            throw new RpaRegisterException("没有签到信息,请先初始化签到！");
        }
        LambdaQueryWrapper<Score> eq = new LambdaQueryWrapper<>();
        buildScoreWrapper(activeDto, eq);
        List<Score> scores = scoreMapper.selectList(eq);
        if (CollUtil.isEmpty(scores)) {
            throw new RpaRegisterException("没有成绩信息,请先初始化/重置成绩！");
        }
        Map<String, Score> scoresMap = scores.stream().collect(Collectors.toMap(
                score -> buildScoreKey(score.getAccountId(), score.getCourseId(), score.getClazzId(), score.getUserName()),
                score -> score,
                (key1, key2) -> key1
        ));
        List<Map<String, Object>> combinedList = new ArrayList<>();
        for (Map<String, Object> active : activeList) {
            // 构建复合键
            String compositeKey = buildScoreKey(MapUtil.getStr(active, "accountId"), MapUtil.getStr(active, "courseId"), MapUtil.getStr(active, "clazzId"), MapUtil.getStr(active, "userName"));

            // 查找匹配的 Score 对象
            Score matchedScore = scoresMap.get(compositeKey);
            Map<String, Object> combinedMap = new HashMap<>(active);
            if (matchedScore != null) {
                combinedMap.put("scoreNumber", matchedScore.getScoreNumber());
                combinedMap.put("scoreType", matchedScore.getScoreType());
                combinedMap.put("scoreId", matchedScore.getId());
                combinedList.add(combinedMap);
            }
        }
        return combinedList;
    }

    private String buildScoreKey(String accountId, String courseId, String clazzId, String userName) {
        return accountId + "_" + courseId + "_" + clazzId + "_" + userName;
    }

    public void buildActiveWrapper(ActiveDto activeDto, QueryWrapper<Active> activeLambdaQueryWrapper) {
        activeLambdaQueryWrapper.eq("a.account_id", activeDto.getAccountId())
                .eq("a.clazz_id", activeDto.getClazzId())
                .eq("a.course_id", activeDto.getCourseId());
        if (StrUtil.isNotBlank(activeDto.getUserNameOrStuNameLike())) {
            activeLambdaQueryWrapper.and(i -> i.like("a.user_name", activeDto.getUserNameOrStuNameLike())
                    .or().like("c.student_number", activeDto.getUserNameOrStuNameLike()));
        }
    }

    @Override
    public List<List<String>> head() {
        List<List<String>> list = Arrays.asList(
                Collections.singletonList("姓名"),
                Collections.singletonList("学号"),
                Collections.singletonList("累计签到"),
                Collections.singletonList("已签到"),
                Collections.singletonList("缺勤"),
                Collections.singletonList("请假"),
                Collections.singletonList("迟到"),
                Collections.singletonList("早退"),
                Collections.singletonList("成绩"));
        return list;
    }

    @Override
    public List<List<Object>> dataList(ActiveDto activeDto) {
        List<List<Object>> list = new ArrayList<>();
        List<Map<String, Object>> activeList = this.getActiveList(activeDto);
        for (Map<String, Object> active : activeList){
            List<Object> row = new ArrayList<>();
            row.add(MapUtil.getStr(active, "userName","-"));
            row.add(MapUtil.getStr(active, "studentNumber","-"));
            row.add(MapUtil.getStr(active, "total","-"));
            row.add(MapUtil.getStr(active, "signed","-"));
            row.add(MapUtil.getStr(active, "unsignedNumber","-"));
            row.add(MapUtil.getStr(active, "leaveNumber","-"));
            row.add(MapUtil.getStr(active, "late","-"));
            row.add(MapUtil.getStr(active, "early","-"));
            row.add(MapUtil.getStr(active, "scoreNumber","-"));
            list.add(row);
        }
        return list;
    }

    private void buildScoreWrapper(ActiveDto activeDto, LambdaQueryWrapper<Score> activeLambdaQueryWrapper) {
        activeLambdaQueryWrapper.eq(Score::getAccountId, activeDto.getAccountId())
                .eq(Score::getClazzId, activeDto.getClazzId())
                .eq(Score::getCourseId, activeDto.getCourseId())
                .eq(Score::getScoreType, 3);
    }
}




